/**
 * 
 */
package org.huanglei.account.view;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import org.huanglei.account.MyApplication;
import org.huanglei.account.R;
import org.huanglei.account.bean.Account;
import org.huanglei.account.provider.DataProvider;
import org.huanglei.account.provider.DataProviderFactory;
import org.huanglei.account.view.base.TitleBarActivity;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * @author huanglei
 * 
 */
public class AccountActivity extends TitleBarActivity {

	private final Context me = this;
	
	Button BtnDate,BtnTime;
	
	TextView dateTV,timeTV;
	
	private int year;
    private int month;
    private int day;
    private int hour;
    private int minute;
    
	@Override
	protected int getContentView() {
		return R.layout.account_edit;
	}

	protected void initTitleBar() {
		setBarTitle(getResources().getString(R.string.account_add));

		showBarView(TitleBarView.TBV_BACK, TitleBarActivity.CL_BACK);

		// 保存按钮
		Button saveBtn = (Button) showBarView(TitleBarView.TBV_WRAPPER_BTN1);
		saveBtn.setVisibility(View.VISIBLE);
		saveBtn.setText(R.string.account_save);
		saveBtn.setOnClickListener(saveClickListener);
		
		BtnDate=(Button)findViewById(R.id.BtnDate);
		BtnDate.setOnClickListener(dClickListener);
		BtnTime=(Button)findViewById(R.id.BtnTime);
		BtnTime.setOnClickListener(tClickListener);
		
	}

	
	@Override
	protected void init() {
		
		MyApplication.getInstance().addActivity(this);
		
		initTitleBar();
		
        //系统加载时间
        initTime();
        //系统加载日期
        setDatetime();
		
        
	}
	
	/**
	 * 获取当前年月日
	 */
	private void initTime(){
		
		Calendar c = Calendar. getInstance(TimeZone.getTimeZone("GMT+08:00"));
		year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH)+1;
        day = c.get(Calendar.DAY_OF_MONTH);
        hour = c.get(Calendar.HOUR_OF_DAY);
        minute = c.get(Calendar.MINUTE);
	}
	
	/**
	 * 获取当前时间
	 */
	private void setDatetime(){
		
		dateTV = (TextView) findViewById(R.id.vdate);
		timeTV = (TextView) findViewById(R.id.vtime);
        
		dateTV.setText(year+"-"+month+"-"+day);
        timeTV.setText(pad(hour)+":"+pad(minute));
	}
	
	/**
	 * 格式化 时间
	 * @param c
	 * @return
	 */
    private static String pad(int c) {
        if (c >= 10){
            return String.valueOf(c);
        }else{
            return "0" + String.valueOf(c);
        }
    }

	/**
	 * 根据数据类型获取输入框值
	 * 
	 * @param id
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private <T> T getEditViewValue(int id, Class<T> clazz) {
		EditText editText = (EditText) findViewById(id);
		String value = editText.getText().toString();
		Object o = null;
		if (clazz.getName().equals(String.class.getName())) {
			o = value;
		}
		if (clazz.getName().equals(Double.class.getName())) {
			o = Double.parseDouble(value);
		}
		if (clazz.getName().equals(Integer.class.getName())) {
			o = Integer.parseInt(value);
		}
		return (T) o;

	}
	
	/** 设置日期 */
	OnClickListener dClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			showDialog(2);
		}
		
	};
	/** 设置时间 */
	OnClickListener tClickListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			showDialog(1);
		}
		
	};
	
	@Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case 1:
                return new TimePickerDialog(this,
                        timeSetListener, hour, minute, false);
            case 2:
                return new DatePickerDialog(this,
                            dateSetListener,
                            year, month-1, day);
        }
        return null;
    }
	
	/**
	 * 弹出层设置 时间
	 */
    private TimePickerDialog.OnTimeSetListener timeSetListener =
            new TimePickerDialog.OnTimeSetListener() {

            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                hour = hourOfDay;
                minute = minute;
                setDatetime();
            }
	};
	
	/**
	 * 弹出层设置 日期
	 */
    private DatePickerDialog.OnDateSetListener dateSetListener =
            new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear,
                    int dayOfMonth) {
                year = year;
                month = monthOfYear+1;
                day = dayOfMonth;

                setDatetime();
            }
	};

	/**
	 * 获取用户数据并提交
	 */
	OnClickListener saveClickListener = new OnClickListener() {

		@Override
		public void onClick(View view) {
			
			// 检测输入数据安全
			EditText moneyEditText = (EditText) findViewById(R.id.account_edit_edt_money);
			if(!"".equals(moneyEditText.getText().toString())){
				
				// 类型
				Spinner spinner = (Spinner) findViewById(R.id.account_edit_sp_type);
				String type = spinner.getSelectedItem().toString();

				// 金额
				double money = getEditViewValue(R.id.account_edit_edt_money, Double.class);
				
				String dt = ((TextView)dateTV).getText().toString()+" "+((TextView)timeTV).getText().toString();
				// 日期
				long date = 0L;
				try {
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); //格式化当前系统日期
					Date date11 = df.parse(dt);
					date = date11.getTime();
					
				} catch (ParseException e) {
					e.printStackTrace();
				}  
				
				// 备注
				String memo = getEditViewValue(R.id.account_edit_edt_memo,
						String.class);
				
				Account account = Account.newAccount().setType(type)
						.setMoney(money).setDate(date).setMemo(memo);

				DataProvider dataProvider = DataProviderFactory.getProvider(me,
						DataProviderFactory.LOCAL);

				dataProvider.save(account);
				
				Toast.makeText(me, "保存成功.", Toast.LENGTH_SHORT).show();
				
				toBackup();
				
			}else{
				Toast.makeText(me, "请输入金额", Toast.LENGTH_SHORT).show();
			}

		}
	};
	
	/**
	 * 保存成功 跳转数据列表
	 */
	private void toBackup(){
        Intent intent = new Intent();  
        intent.setClass(AccountActivity.this, AccountListActivity.class);  
        startActivity(intent);
	}
}
